package common

import (
	"fmt"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/lwa"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	common "gitee.com/alex_li/amazon-rpt/internal/sdk/amazon"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/go-log"
)

func CreateSdk(client db.AmazonLwa) (sdk *advertising.Client, err error) {

	var token lwa.AccessToken
	var tokenDb db.AmazonToken
	var profile db.AmazonAdsProfile
	err = app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		e = tx.Context.QueryTable(new(db.AmazonToken)).
			Filter("ClientId", client.ClientId).
			One(&tokenDb)
		if e != nil {
			return
		}
		token.RefreshToken = tokenDb.RefreshToken
		token.AccessToken = tokenDb.AccessToken
		token.ExpiresIn = tokenDb.Expires
		token.ApplyAt = tokenDb.ApplyAt
		var profiles []db.AmazonAdsProfile
		_, e = tx.Context.QueryTable(new(db.AmazonAdsProfile)).
			Filter("ClientId", client.ClientId).
			Limit(10).
			All(&profiles)
		if e != nil {
			log.Info(err)
			return
		}
		if len(profiles) > 0 {
			profile = profiles[0]
		}
		return
	})
	if err != nil {
		log.Info(err)
		return
	}
	connector := lwa.New(client.ClientId, client.Secret, token.RefreshToken)
	sdk = advertising.New(advertising.WithLwa(connector, func(newToken lwa.AccessToken) {
		go saveToken(client, newToken)
	}),
		advertising.WithLwaToken(token),
		advertising.WithTokenErrorListener(func(clientId string, err error) {
			log.Info("token error:", err)
		}),
		advertising.WithMarketplace(common.Us, true),
		advertising.WithProfile(profile.ProfileId),
	)
	return
}

func saveToken(client db.AmazonLwa, token lwa.AccessToken) {
	err := app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		var tmp db.AmazonToken
		e = tx.Context.QueryTable(new(db.AmazonToken)).
			Filter("ClientId", client.ClientId).
			One(&tmp)
		if e == nil {
			tmp.AccessToken = token.AccessToken
			tmp.ApplyAt = token.ApplyAt
			tmp.Expires = token.ExpiresIn - 30
			_, e = tx.Context.Update(&tmp, "AccessToken", "ApplyAt", "Expires")
		} else {
			log.Info("create token")
			tmp.ClientId = client.ClientId
			tmp.AccessToken = token.AccessToken
			tmp.RefreshToken = token.RefreshToken
			tmp.ApplyAt = token.ApplyAt
			tmp.Expires = token.ExpiresIn - 30
			tmp.Status = 10
			_, e = tx.Context.Insert(&tmp)
		}
		return
	})
	if err != nil {
		log.Info(err)
	}
}

func GetMyClient(clientId string) (client db.AmazonLwa, err error) {
	var list []db.AmazonLwa
	_, err = app.GetOrm().Context.QueryTable(new(db.AmazonLwa)).
		Filter("ClientId", clientId).
		Limit(1).
		All(&list)
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) == 0 {
		err = fmt.Errorf("empty")
		log.Info(err)
		return
	}
	client = list[0]
	return
}

func GetClient(from int) (client db.AmazonLwa, err error) {
	var list []db.AmazonLwa
	_, err = app.GetOrm().Context.QueryTable(new(db.AmazonLwa)).
		Filter("id__gt", from).
		Limit(1).
		All(&list)
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) == 0 {
		err = fmt.Errorf("empty")
		log.Info(err)
		return
	}
	client = list[0]

	return
}

func GetToken(clientId string) (token lwa.AccessToken, err error) {
	var list []lwa.AccessToken
	_, err = app.GetOrm().Context.QueryTable(new(db.AmazonToken)).Filter("", "").All(&list)
	if err != nil {
		return
	}
	if len(list) == 0 {
		err = fmt.Errorf("empty")
		return
	}
	token = list[0]
	return
}
